var schInfoAPI = (function ($) {
	var thisYM = ''
	var currYM = ''
	var today = ''
	var perId = '',nurseid = ""
	$.init();
	$.plusReady(function () {
	    baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}
	
	function getServerTime(){
		today = getCurrentDeviceDay() ;//'2021-08-11'
		thisYM = today.substring(0,today.length - 3);
		currYM = thisYM
		getMySchData(today)
	}
	function getMySchData(ymdStr){
		$('#listWrapper').scroll().scrollTo(0,0,100);
		updateMyScheduleBodyUI(ymdStr)
		var startDate = $('#myBody')[0].querySelector('td').id.replace('my-','')
		var pdict = {'loginID':nurseid,'parr':startDate,'appFlag':'1','appRet':''}
		var paramDict = {'method':'web.INMPlatform:FindUserArgList','params':JSON.stringify(pdict),'type':'MethodNoFilter'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			getChosenSchData()
			if (!result['data']) {
				return
			}
			updateMyScheduleBodyContent(result['data'])
			
		}, function(errorStr) {
			mui.toast('请重试')
		});
	}
	function getChosenSchData(){
		var chosen = $('#myBody .chosen')[0]
		if (!chosen) {
			return
		}
		var dateStr = chosen.id.replace('my-','')
		var pdict = {'perId':perId,'date':dateStr,'appFlag':'1','appRet':''}
		var paramDict = {'method':'web.INMArgComm:GetPerDayArgInfo','params':JSON.stringify(pdict),'type':'MethodNoFilter'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (!result['data']) {
				clearMiddleCardUI()
				return
			}
			myMidCardUI(result['data'])
			
		}, function(errorStr) {
			mui.toast('请重试')
			clearMiddleCardUI()
		});
	}
	
	function myMidCardUI(dataDict){
		//myMidCardUI(result['data'])
		mui('#myMidCard .oneSchArea').each(function (index,element) {
			$('#myMidCard')[0].removeChild(element)
		})
		var post = dataDict['Post']
		if (!post) {
			return
		}
		var myMidCard = $('#myMidCard')[0]
		var staticArea = $('#staticArea')[0]
		for (var i = 0; i < post.length; i++) {
			var onePost = post[i]
			var dom = document.createElement('div')
			dom.classList.add('oneSchArea')
			var timeStr = onePost['StTime1']+' - '+onePost['EndTime1']
			if (onePost['StTime2']) {
				timeStr += ';' + onePost['StTime2']+' - '+onePost['EndTime2']
			}
			if (onePost['StTime3']) {
				timeStr += ';' + onePost['StTime3']+' - '+onePost['EndTime3']
			}
			dom.innerHTML = '<div class="oneSchText">'+onePost['PostDesc']+
				'<div class="oneSchTime">（ '+timeStr+' ）</div></div>'+
				'<div class="oneSchMark">备注: '+onePost['Remark']+'</div>'
			myMidCard.insertBefore(dom,staticArea)
		}
		$('#weekTotal')[0].innerHTML = '本周总工时&nbsp;&nbsp;'+dataDict['WeekHours']+'小时'
		$('#remainder')[0].innerHTML = '累计欠存&nbsp;&nbsp;'+dataDict['YearHours']+'小时'
	}
	function clearMiddleCardUI(){
		mui('#myMidCard .oneSchArea').each(function (index,element) {
			$('#myMidCard')[0].removeChild(element)
		})
		$('#weekTotal')[0].innerHTML = '本周总工时'
		$('#remainder')[0].innerHTML = '累计欠存'
	}
	
	function updateMyScheduleBodyContent(dataDict){
		mui('#myBody td').each(function (index,td) {
			var dom = td.querySelector('.daySch')
			var dateStr = td.id.replace('my-','')
			setOneSchHtml(dom,dataDict[dateStr]);
		})
		mui('#myBodyList tr').each(function (index,tr) {
			var dom = tr.querySelector('.listSch')
			var dateStr = tr.id.replace('list-','')
			setOneSchHtml(dom,dataDict[dateStr]);
		})
	}
	
	function setOneSchHtml(dom,schArr){
		if (!schArr) {
			return
		}
		var html = ''
		for (var i = 0; i < schArr.length; i++) {
			var oneSch = schArr[i]
			html += '<div class="schUnit" style="'
			if (oneSch['BgColor'] != '') {
				html += 'background:'+oneSch['BgColor']+';'
			}
			if (oneSch['FontColor'] != '') {
				html += 'color:'+oneSch['FontColor']+';'
			}
			html += '">'+oneSch['Desc']+'</div>'
		}
		dom.innerHTML = html
	}
	
	function updateMyScheduleBodyUI(ymdStr){
		$('#myBody').off('tap','td',selectOneDay);
		$('#myBodyList').off('tap','tr',selectOneDay);
		var ymDict = getYMDWithStr(ymdStr)
		$('#ymDate')[0].innerText = outChinaYMStr2(ymDict.year,ymDict.month)
		$('#myBody')[0].setAttribute('data-parr',ymdStr)
		var year = ymDict.year;
		var month = ymDict.month
		currYM = outYMStr(year,month);
		var maxDay = getMonthMaxDay(year, month);
		var lastMaxDay = getLastMonthMaxDay(year, month);
		var ymStr = outYMStr(year, month)
		var startIndex = getWeekIndex(ymStr + '-01');//1到7
		var endIndex = getWeekIndex(ymStr + '-' + maxDay);
		if (startIndex == 0) {
			startIndex = 7
		}
		if (endIndex == 0) {
			endIndex = 7
		}
		var count = startIndex + maxDay + (6 - endIndex);
		
		var startDate = '';
		var endDate = '';
		var html = '';
		var listHtml = ''
		var weekArr = ['一','二','三','四','五','六','日'];
		for(var i = 0; i < count; i++) {
			var curIndex = i % 7
			if(i % 7 == 0) {
				html += '<tr class="schTr">';
			}
			if(i < startIndex - 1) { //上个月的
				var dayStr = lastMaxDay - (startIndex-1) + i + 1;
				var lmonth = month - 1;
				var lyear = year;
				if(lmonth == 0) {
					lmonth = 12;
					lyear -= 1;
				}
				var idStr = '' + lyear + '-' + lmonth + '-' + dayStr;
				if(lmonth < 10) {
					idStr = '' + lyear + '-0' + lmonth + '-' + dayStr;
				}
				if (i == 0) {
					startDate = idStr
				}
				html += '<td class="abnormal" valign="top" id="my-'+idStr+'"><div class="oneDay">' + dayStr + '</div><div class="daySch"></div></td>';
			} else if(i >= (startIndex-1) + maxDay) { //下个月
				var nmonth = month + 1;
				var nyear = year;
				if(nmonth == 13) {
					nmonth = 1;
					nyear += 1;
				}
				var dayStr = (i - maxDay - (startIndex-1) + 1);
				var idStr = '' + nyear + '-' + nmonth + '-0' + dayStr;
				if(nmonth < 10) {
					idStr = '' + nyear + '-0' + nmonth + '-0' + dayStr;
				}
				if (i == count -1) {
					endDate = idStr
				}
				html += '<td class="abnormal" valign="top" id="my-'+idStr+'"><div class="oneDay">' + dayStr + '</div><div class="daySch"></div></td>';
			} else {
				var monthStr = month + '';
				var dayStr = (i - (startIndex-1) + 1);
				var listStr = monthStr +'月'+dayStr+'日'+'&nbsp;&nbsp;星期'+weekArr[i % 7]
				if (month < 10) {
					monthStr = '0'+month;
				}
				var idStr = '' + year +'-'+monthStr + '-' + dayStr;
				if((i - (startIndex-1) + 1) < 10) {
					idStr = '' + year +'-'+monthStr + '-0' + dayStr;
				}
				
				var classStr =""
				if (idStr == '' + today) { //今天
					classStr = 'today chosen'
				}
				if (i == 0) {
					startDate = idStr
				}else if (i == count -1) {
					endDate = idStr
				}
				
				html += '<td class="'+classStr+'" valign="top" id="my-'+idStr+'"><div class="oneDay">' + dayStr + '</div><div class="daySch"></div></td>';
				
				listHtml += '<tr id="list-'+idStr+'" class="'+classStr+'"><td>'+listStr+'</td><td class="listSch"></td></tr>'
			}
			if(i % 7 == 6) {
				html += '</tr>';
			}
		}
		var myBody = $('#myBody')[0];
		myBody.innerHTML = html;
		$('#myBody').on('tap','td',selectOneDay);
		var listWrapper = $('#listWrapper')[0];
		// listWrapper.style.height = $('#mySchedule')[0].clientHeight + 'px'
		$('#myBodyList')[0].innerHTML = listHtml
		$('#myBodyList').on('tap','tr',selectOneDay);
	}
	function selectOneDay(){
		if (this.getAttribute('class').indexOf('abnormal') != -1) {
			return;
		}
		var oldChosen = $('#myBody .chosen')[0]
		if (oldChosen == this) {
			getChosenSchData();
			return;
		}
		if (oldChosen) {
			oldChosen.classList.remove('chosen')
		}
		var oldListChosen = $('#myBodyList .chosen')[0]
		if (oldListChosen) {
			oldListChosen.classList.remove('chosen')
		}
		this.classList.add('chosen')
		var domId = this.id
		if (domId.indexOf('my-') != -1) {
			domId = domId.replace('my-','list-')
		}else{
			domId = domId.replace('list-','my-')
		}
		$('#'+domId)[0].classList.add('chosen')
		getChosenSchData();
	}

	function selectYearMonth() {
		var _self = this
		_self.classList.add('mui-active')
		if(_self.picker) {
			_self.picker.show(function(rs) {
				getMySchData(rs.text+'-01')
				_self.classList.remove('mui-active')
				_self.picker.dispose();
				_self.picker = null;
				
			});
		} else {
			var optionsJson = '{"type":"month"}';
			var options = JSON.parse(optionsJson);
			_self.picker = new mui.DtPicker(options);
			_self.picker.show(function(rs) {
				getMySchData(rs.text+'-01')
				_self.classList.remove('mui-active')
				_self.picker.dispose();
				_self.picker = null;
			});
		}
	}
	
	function iOSselectDatePicker(){
		plus.nativeUI.pickDate(function(e) {
			var d = e.date;
			var dateStr = d.getFullYear() + '-'
			if (d.getMonth() < 9) {
				dateStr += '0'
			}
			dateStr += d.getMonth() + 1
			getMySchData(dateStr+'-01')
		}, function(e) {}, {});
	}
	
	function baseSetup(){
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		var self = plus.webview.currentWebview()
		if (!self.title) {
			document.body.removeChild(mui('#bar')[0])
			//mui('#bar')[0].removeAttribute('style')
		}
		var perInfo = app.getState()
		var maxRoleLevel = perInfo['maxRoleLevel']||''
		if (maxRoleLevel != '' && parseInt(maxRoleLevel) <= 4) {
			$('#toSchBtn')[0].removeAttribute('style')
		}
		perId = perInfo['loginPerID']
		nurseid = perInfo['loginID']
		getServerTime();
		var slider = document.getElementById('slider');
		slider.addEventListener('slide', function(event) {
			var index = event.detail.slideNumber;
			$('#sliderIndicator .mui-indicator[data-index="'+index+'"]')[0].classList.add('mui-active');
		});
		var indicators = document.querySelectorAll('#sliderIndicator .mui-indicator');
		for (var i = 0; i < indicators.length;i++) {
			indicators[i].addEventListener('tap',function(){
				var oldActive = $('#sliderIndicator .mui-indicator.mui-active')[0];
				if (oldActive) {
					if (oldActive == this) {
						return
					}
					oldActive.classList.remove('mui-active')
				}
				var newIndex = parseInt(this.getAttribute('data-index'))
				this.classList.add('mui-active')
				mui('#slider').slider().gotoItem(newIndex,100)
			});
		}

		$('.myHeader').on('tap', '#changeYM', iOSselectDatePicker);
		$('.myHeader').on('tap', '#changeMode', function() {
			var myHeadCard = $('#myHeadCard')[0];
			var img = this.querySelector('img')
			if (myHeadCard.getAttribute('class').indexOf('listMode') != -1) {
				this.classList.remove('mui-active')
				myHeadCard.classList.remove('listMode')
				setTimeout(function() {
					img.src="../../dependence/teach/images/file_block.svg"
				}, 200);
			} else {
				this.classList.add('mui-active')
				myHeadCard.classList.add('listMode')
				setTimeout(function() {
					img.src="../../dependence/teach/images/file_list.svg"
				}, 200);
			}
		});
		mui('body').on('tap','.mui-dtpicker-header > button',function(e){
			$('#changeYM')[0].classList.remove('mui-active')
		});
		mui("body").on("tap",".mui-backdrop",function(){
			$('#changeYM')[0].classList.remove('mui-active')
			$('#locName')[0].classList.remove('mui-active')	
		})
		mui(".myApplyCard").on("tap",".myApply",function(){
			var title = this.querySelector('.applyText').innerText;
			var imgSrc = this.querySelector('.applyImg').getAttribute('src');
			var webview = plus.webview.create('nurSchAppList.html', 'nurSchAppList', {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			},{'title':title,'imgSrc':imgSrc});
			webview.show('fade-in');
		})
		mui("body").on("tap","#toSchBtn",function(){
			var locDom = $('#locText')[0]
			var webview = plus.webview.create('nurSchLoc.html', 'nurSchLoc', {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			},{'wardID':locDom.getAttribute('data-id'),'wardDesc':locDom.innerText});
			webview.show('fade-in');
			webview.addEventListener('close',locPageClose)
			
		})
		//
		mui("body").on("tap","#staticArea",function(){
			var webview = plus.webview.create('nurSchPerStat.html', 'nurSchPerStat', {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			},{'currYM':currYM,'perId':perId});
			webview.show('fade-in');
		})
		//APPMenu 菜单显示与否
		var APPMenu = app.getState().APPMenu
		if (!APPMenu) {
			return
		}
		mui('.noPermission').each(function (domIndex,dom) {
			var code = dom.getAttribute('data-menu')
			if (code && code!="" && APPMenu[code]) {
				dom.classList.remove('noPermission')
			}
		})
	}
	function locPageClose(){
		//个人排班更新
		getMySchData($('#myBody')[0].getAttribute('data-parr'));
		//科室排班更新
		pageBackGetLocSchData()
	}
	
	var changeDefaultLoc = function(){
		var user = app.getState();
		console.log(user.loginWardDesc)
		console.log(user.loginWardId)
	}
	var api = {};
	api.refresh = changeDefaultLoc;
	return api;
})(mui);

function reloadDefaultLoc(){
	schInfoAPI.refresh()
}